package cc.c3p0.admin.module.group.service.impl;

import cc.c3p0.admin.common.dto.Tree;
import cc.c3p0.admin.common.mapper.BasicMapper;
import cc.c3p0.admin.common.service.impl.BasicServiceImpl;
import cc.c3p0.admin.module.group.service.GroupServiceI;
import cc.c3p0.admin.mybatis.mapper.AdminGroupMapper;
import cc.c3p0.admin.mybatis.mapper.AdminResourceMapper;
import cc.c3p0.admin.mybatis.mapper.AdminRoleMapper;
import cc.c3p0.admin.mybatis.model.AdminGroup;
import cc.c3p0.admin.mybatis.model.AdminResource;
import cc.c3p0.admin.mybatis.model.AdminRole;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户组业务实现
 * Created by binchao on 2017/4/7.
 */
@Service
public class GroupServiceImpl extends BasicServiceImpl<AdminGroup> implements GroupServiceI {

    @Resource
    private AdminGroupMapper groupMapper;

    @Resource
    private AdminRoleMapper roleMapper;

    @Resource
    private AdminResourceMapper resourceMapper;

    @Override
    protected BasicMapper<AdminGroup> getMapper() {
        return groupMapper;
    }

    @Override
    public void grantRole(String id, String rIds) {
        AdminGroup group = new AdminGroup();
        group.setId(id);
        group.setRids(rIds);
        groupMapper.updateByPrimaryKeySelective(group);
    }

    @Override
    public Boolean checkPermision(String userId, String path) {
        return null;
    }

    @Override
    public List<Tree> getGroupTree(String id) {
        List<Tree> list = new ArrayList<>();
        AdminGroup group = groupMapper.selectByPrimaryKey(id);
        if (!StringUtils.isEmpty(group.getRids())) {
            List<AdminRole> roleList = roleMapper.selectByIds(group.getRids().split(","));
            Tree root = new Tree();
            root.setTitle(group.getName());
            List<Tree> groupChild = new ArrayList<>();
            for (AdminRole role : roleList) {
                Tree roleTree = new Tree();
                roleTree.setTitle(role.getName());

                if (!StringUtils.isEmpty(role.getRids())) {
                    List<Tree> roleChild = resourceMapper.getResourceByIds(role.getRids().split(","));
                    roleTree.setChildren(roleChild);
                }

                groupChild.add(roleTree);
            }
            root.setChildren(groupChild);
            list.add(root);
        }
        return list;
    }
}
